/**
 * This class contains a patient's balance sheet.
 */
public class Billing {
	private String patient;
	private int balance;

	/**
	 * Creates a new instance of a given patient's Billing record
	 * 
	 * @param patient
	 *            the given patient
	 */
	public Billing(String username) {
		this.patient = username;
		this.balance = 0;
	}

	/**
	 * Returns the patient associated with this bill
	 * 
	 * @return the patient associated with this bill
	 */
	public String getPatient() {
		return patient;
	}

	/**
	 * Sets the patient associated with this bill
	 * 
	 * @param patient
	 *            the patient associated with this bill
	 */
	public void setPatient(String patient) {
		this.patient = patient;
	}

	/**
	 * Returns the balance of this bill
	 * 
	 * @return the balance of this bill
	 */
	public int getBalance() {
		return balance;
	}

	/**
	 * Sets the balance of this bill
	 * 
	 * @param balance
	 *            the new balance of this bill
	 */
	public void setBalance(int balance) {
		this.balance = balance;
	}

	/**
	 * Calculates the cost of a filled out order
	 * 
	 * @return 42 because we do not yet have a better answer.
	 */
	public int calculateCost(String orders) {
		return 42;
	}

	// CRUD

	// Create
	public static int createBilling(String username, int balance) {
		Billing bill = readBilling(username);
		if (bill.getBalance == 0) {
			String sql = "INSERT INTO Billing VALUES ('" + username + "', '"
					+ balance + "')";
			int rows = Database.query(sql);
			if (rows == 1)
			{
				return true;
			}
			else
			{
				return false;
			}
		} else {
			return updateBilling(bill.getPatient(), bill, getBalance());
		}
	}

	// Read
	public static Billing readBilling(String username) {
		String sql = "SELECT * FROM Billing WHERE username='" + username + "'";
		ResultSet rs = Database.selectQuery(sql);
		int balance = 0;
		try {
			while (rs.next()) {
				balance = rs.getInt("balance");
			}
		} catch (Exception E) {
		}
		Billing bill = new Billing(username);
		bill.setBalance(balance);
		return bill;
	}

	// Update
	public static int updateBilling(String username, int balance) {
		String sql = "UPDATE Billing SET balance='" + balance
				+ "' WHERE username='" + username + "'";
		int rows = Database.query(sql);
		if (rows == 1) {
			return true;
		} else {
			return false;
		}
	}

	// Delete
	public static int deleteBilling(String username) {
		String sql = "DELETE FROM Billing WHERE username='" + username + "'";
		int rows = Database.query(sql);
		if (rows == 1) {
			return true;
		} else {
			return false;
		}
	}
}
